package com.hrupin;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;





public class HelloAndroidGpsActivity extends Activity implements
		LocationListener {

	public float soft_speed_limit = 15;
	public float gps_accuracy_limit = 35;
	private int gps_update_interval = 1000;//3000;



  public String pub_COLUMN_NAME_GPS_LAT = "-";
	public String pub_COLUMN_NAME_GPS_LON = "-";
	public String pub_COLUMN_NAME_GPS_ACCURACY = "-";
	public String pub_COLUMN_NAME_GPS_SPEED = "-";
	public String pub_COLUMN_NAME_OSM_ID = "-";
	public String pub_COLUMN_NAME_OSM_ROAD = "-";
	public String pub_COLUMN_NAME_OSM_TAG_MAXSPEED = "-";
	public String pub_COLUMN_NAME_OSM_TAG_HIGHWAY = "-";
	public String pub_COLUMN_NAME_OSM_TAG_NAME = "-";
	public String pub_COLUMN_NAME_OSM_ID_XML = "-";
	public String pub_COLUMN_NAME_OSM_TAG_XML = "-";
	public String pub_COLUMN_NAME_USER_SPEED = "-";


	private TextView lonViwe;
	private TextView latViwe;
	private TextView gpsspeedViwe;
	private TextView osmspeedViwe;
	private TextView userspeedViwe;
	private TextView accuracyViwe;
	private TextView infoViwe;

//	Button b1;
//	Button b2;

	private LocationManager locationManager;
	private String last_osm_id = "";
	

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				gps_update_interval, 1, this);

		setContentView(R.layout.main);
		lonViwe = (TextView) findViewById(R.id.lon);
		latViwe = (TextView) findViewById(R.id.lat);
		gpsspeedViwe = (TextView) findViewById(R.id.gpsspeed);
		osmspeedViwe = (TextView) findViewById(R.id.osmspeed);
		userspeedViwe = (TextView) findViewById(R.id.userspeed);
		accuracyViwe = (TextView) findViewById(R.id.accuracy);
		infoViwe = (TextView) findViewById(R.id.info);
		
//		b1 = (Button) findViewById(R.id.speed40);
//	    b2 = (Button) findViewById(R.id.speed50);
//	    b1.setOnClickListener(myhandler1);
//	    b2.setOnClickListener(myhandler2);

		insertIntoTable();
	
	}

	
	private class change_speed_color extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			change_speed_color();
			return "";
		}
		@Override
		protected void onPostExecute(String result) {
		}
	}
	public void async_change_speed_color() {
		change_speed_color task = new change_speed_color();
		task.execute();
	}
	public void change_speed_color() {
		runOnUiThread(new Runnable() {
		     public void run() {

		//stuff that updates ui

		Float float_pub_COLUMN_NAME_GPS_ACCURACY = 999f;
		try {
			float_pub_COLUMN_NAME_GPS_ACCURACY = Float.parseFloat(pub_COLUMN_NAME_GPS_ACCURACY);
		} catch (Exception e) {
			float_pub_COLUMN_NAME_GPS_ACCURACY = 999f;
		}
		
		Float float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED = 999f;
		try {
			float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED = Float.parseFloat(pub_COLUMN_NAME_OSM_TAG_MAXSPEED);
		} catch (Exception e) {
			float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED = 999f;
		}
		
		Float float_pub_COLUMN_NAME_GPS_SPEED = 0f;
		try {
			float_pub_COLUMN_NAME_GPS_SPEED = Float.parseFloat(pub_COLUMN_NAME_GPS_SPEED);
		} catch (Exception e) {
			float_pub_COLUMN_NAME_GPS_SPEED = 0f;
		}
		
		Float float_pub_COLUMN_NAME_USER_SPEED = 999f;
		try {
			float_pub_COLUMN_NAME_USER_SPEED = Float.parseFloat(pub_COLUMN_NAME_USER_SPEED);
		} catch (Exception e) {
			float_pub_COLUMN_NAME_USER_SPEED = 999f;
		}
		
		try {
			if ( float_pub_COLUMN_NAME_GPS_ACCURACY <= gps_accuracy_limit ){
				if (float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED > 0 ) {
					if ( float_pub_COLUMN_NAME_GPS_SPEED >= float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED ) {
						if ( float_pub_COLUMN_NAME_GPS_SPEED >= (float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED + soft_speed_limit) ) {
							//red
							gpsspeedViwe.setTextColor(Color.RED);
							Log.d("GPS", "Speed - Red");
						} else {
							//yellow
							gpsspeedViwe.setTextColor(Color.YELLOW);
							Log.d("GPS", "Speed - Yellow");
						}
					}
				} else if (float_pub_COLUMN_NAME_USER_SPEED > 0) {
					if ( float_pub_COLUMN_NAME_GPS_SPEED >= float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED ) {
						if ( float_pub_COLUMN_NAME_GPS_SPEED >= (float_pub_COLUMN_NAME_OSM_TAG_MAXSPEED + soft_speed_limit) ) {
							//red
							gpsspeedViwe.setTextColor(Color.RED);
							Log.d("GPS", "Speed - Red");
						} else {
							//yellow
							gpsspeedViwe.setTextColor(Color.YELLOW);
							Log.d("GPS", "Speed - Yellow");
						}
					}
				}
			} else {
				//green
				gpsspeedViwe.setTextColor(Color.GREEN);
				Log.d("GPS", "Speed - Green");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
			    }
			});
	}
	

	
    // Initiating Menu XML file (menu.xml)
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
 
        switch (item.getItemId())
        {
        case R.id.menu_exit:
            this.onDestroy();
            return true; 
 
        case R.id.menu_send_db:
            this.sendDatabase();
            return true; 
 
        case R.id.menu_clear_db:
            this.clearDatabase();
            return true; 
 
        default:
            return super.onOptionsItemSelected(item);
        }
    } 
	

    private final String toSenders = "jmasalma@gmail.com";
    private final String subjectText = "Database File";
    private final String messageText = "Attached";
    private final String emailSignature = "Sign";
    

    public void sendDatabase() {

      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
//      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailSignature);
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, toSenders);
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subjectText);
      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, messageText+"\n\n"+emailSignature); 

      emailIntent.setType("image/jpeg");
      File dbFile = new File("/data/data/"
              + getApplicationContext().getPackageName()
              + "/databases/" + DATABASE_NAME);
      Uri myUri = Uri.fromFile(dbFile);
      emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);


      startActivity(Intent.createChooser(emailIntent, "Send your email in:"));
      //eraseContent();
      //sentMode = true;
		Log.d("GPS", "Database emailed");
    }

	public void clearDatabase() {
		DBHelper androidOpenDbHelperObj = new DBHelper(this);
		SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
		sqliteDatabase.execSQL("delete from " + DBHelper.TABLE_NAME_SPEED_LIMIT);
		Log.d("GPS", "Database cleared");
	}

    
    
/*
	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String osm_id = getOSMID(urls[0]);
			if (osm_id.equals("")) return "";
			return getOSMSpeed(osm_id);
		}

		@Override
		protected void onPostExecute(String result) {
			//lon.setText(result);
			osmspeedViwe.setText(result);
		}
	}
*/
	private class GetOSMIDTask extends AsyncTask<String, Void, String[]> {
		@Override
		protected String[] doInBackground(String... urls) {
			String[] osm_id = getOSMID(urls[0]);
			/*if (osm_id[0].equals("")) 
				return (new String[] {"",""});
			else*/
			return osm_id;
		}

		@Override
		protected void onPostExecute(String[] result) {
			if (!result[1].equals(""))
				infoViwe.setText(result[1]);
			if (!result[0].equals("")) {
				GetOSMSpeedTask task = new GetOSMSpeedTask();
				task.execute(new String[] { result[0] });
			}
		}
	}

	
	private class AddToDatabase extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			async_insertIntoTable();
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
		}
	}

	public void async_insertIntoTable() {
		DBHelper androidOpenDbHelperObj = new DBHelper(this);
		SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		//contentValues.put(DBHelper.COLUMN_NAME_TS, "datetime()");
		contentValues.put(DBHelper.COLUMN_NAME_GPS_LAT, pub_COLUMN_NAME_GPS_LAT);
		contentValues.put(DBHelper.COLUMN_NAME_GPS_LON, pub_COLUMN_NAME_GPS_LON);
		contentValues.put(DBHelper.COLUMN_NAME_GPS_ACCURACY, pub_COLUMN_NAME_GPS_ACCURACY);
		contentValues.put(DBHelper.COLUMN_NAME_GPS_SPEED, pub_COLUMN_NAME_GPS_SPEED);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_ID, pub_COLUMN_NAME_OSM_ID);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_ROAD, pub_COLUMN_NAME_OSM_ROAD);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_TAG_MAXSPEED, pub_COLUMN_NAME_OSM_TAG_MAXSPEED);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_TAG_HIGHWAY, pub_COLUMN_NAME_OSM_TAG_HIGHWAY);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_TAG_NAME, pub_COLUMN_NAME_OSM_TAG_NAME);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_ID_XML, pub_COLUMN_NAME_OSM_ID_XML);
		contentValues.put(DBHelper.COLUMN_NAME_OSM_TAG_XML, pub_COLUMN_NAME_OSM_TAG_XML);
		contentValues.put(DBHelper.COLUMN_NAME_USER_SPEED, pub_COLUMN_NAME_USER_SPEED);

		// Now we can insert the data in to relevant table
		// I am going pass the id value, which is going to change because of our insert method, to a long variable to show in Toast
		long affectedColumnId = sqliteDatabase.insert(DBHelper.TABLE_NAME_SPEED_LIMIT, null, contentValues);

		// It is a good practice to close the database connections after you have done with it
		sqliteDatabase.close();

		// I am not going to do the retrieve part in this post. So this is just a notification for satisfaction ;-) 
		//Toast.makeText(this, "Values inserted column ID is :" + affectedColumnId, Toast.LENGTH_SHORT).show();

		Log.d("GPS", "Values inserted column ID is :" + affectedColumnId);
	}

	public void insertIntoTable() {
		AddToDatabase task = new AddToDatabase();
		task.execute();

	}
	
	
    private final String DATABASE_NAME = "speed_limit_006.db";
    private final int DATABASE_VERSION = 1; 
	
	public class DBHelper extends SQLiteOpenHelper {   

		public static final String DB_NAME = "undergraduate_gpa_db";
		public static final int DB_VERSION = 1;

		// Table attributes
		public static final String TABLE_NAME_SPEED_LIMIT = "speed_limit";
		public static final String COLUMN_NAME_TS = "sl_ts";
		public static final String COLUMN_NAME_GPS_LAT = "sl_lat";
		public static final String COLUMN_NAME_GPS_LON = "sl_lon";
		public static final String COLUMN_NAME_GPS_ACCURACY = "sl_gps_accuracy";
		public static final String COLUMN_NAME_GPS_SPEED = "sl_gps_speed";
		public static final String COLUMN_NAME_OSM_ID = "sl_osm_id";
		public static final String COLUMN_NAME_OSM_ROAD = "sl_osm_road";
		public static final String COLUMN_NAME_OSM_TAG_MAXSPEED = "sl_osm_tag_maxspeed";
		public static final String COLUMN_NAME_OSM_TAG_HIGHWAY = "sl_osm_tag_highway";
		public static final String COLUMN_NAME_OSM_TAG_NAME = "sl_osm_tag_name";
		public static final String COLUMN_NAME_OSM_ID_XML = "sl_osm_id_xml";
		public static final String COLUMN_NAME_OSM_TAG_XML = "sl_osm_tag_xml";
		public static final String COLUMN_NAME_USER_SPEED = "sl_user_speed";

	    public DBHelper(Context context) {
	        super(context, DATABASE_NAME, null, DATABASE_VERSION);
	    }

	    @Override
	    public void onCreate(SQLiteDatabase db) {
	    	String sqlQueryToCreateUndergraduateDetailsTable = "create table if not exists " + TABLE_NAME_SPEED_LIMIT + " ( " + BaseColumns._ID + " integer primary key autoincrement, " 
			+ COLUMN_NAME_TS + " datetime default CURRENT_DATE, "
	    	+ COLUMN_NAME_GPS_LAT + " text not null, "
	    	+ COLUMN_NAME_GPS_LON + " text not null, "
	    	+ COLUMN_NAME_GPS_ACCURACY + " text not null, "
	    	+ COLUMN_NAME_GPS_SPEED + " text not null, "
	    	+ COLUMN_NAME_OSM_ID + " text not null, "
	    	+ COLUMN_NAME_OSM_ROAD + " text not null, "
	    	+ COLUMN_NAME_OSM_TAG_MAXSPEED + " text not null, "
	    	+ COLUMN_NAME_OSM_TAG_HIGHWAY + " text not null, "
	    	+ COLUMN_NAME_OSM_TAG_NAME + " text not null, "
	    	+ COLUMN_NAME_OSM_ID_XML + " text not null, "
	    	+ COLUMN_NAME_OSM_TAG_XML + " text not null, "
	    	+ COLUMN_NAME_USER_SPEED + " text not null);";
	    	db.execSQL(sqlQueryToCreateUndergraduateDetailsTable);
	    }

	    @Override
	    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if(oldVersion == 1 && newVersion == 2){
				// Upgrade the database
			}		
		}

	}   
	
	
	private class GetOSMSpeedTask extends AsyncTask<String, Void, String[]> {
		@Override
		protected String[] doInBackground(String... osm_id) {
			String[] OSMSpeed = getOSMSpeed(osm_id[0]);
			return OSMSpeed;
		}

		@Override
		protected void onPostExecute(String[] result) {
			if (!result[0].equals(""))
				osmspeedViwe.setText(result[0]);
			if (!result[1].equals(""))
				infoViwe.setText(result[1] + " - " + result[2]);
		}
	}
	
	
	public void setUserSpeed(View view) {
		String userSpeed = ((Button)view).getText().toString();
		if (userSpeed != pub_COLUMN_NAME_USER_SPEED) {
			pub_COLUMN_NAME_USER_SPEED = userSpeed;
			async_change_speed_color();
		}
		insertIntoTable();
		userspeedViwe.setText(userSpeed);

	}
	
	
	/*
	public void readWebpage(View view) {
		DownloadWebPageTask task = new DownloadWebPageTask();
		task.execute(new String[] { "http://nominatim.openstreetmap.org/reverse?lat=43.4618&lon=80.5311" });

	}
*/
	// -----------------------------------------------------------

	// TODO Keep screen on
	// TODO show time since last update
	// TODO Store results in a DB and maybe sync it...
	// TODO show gauge with speed and max speed as last seen...

	public final String[] getOSMID(String url) {

		String osm_id = "";
		String osm_road = "";
		InputStream in = null;
		InputStream in2 = null;
		InputStreamReader reader = null;
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response = httpClient.execute(httpPost, localContext);
			in = response.getEntity().getContent();

			reader = new InputStreamReader(in);
            StringBuffer sb = new StringBuffer();
            {
                int read;
                char[] cbuf = new char[1024];
                while ((read = reader.read(cbuf)) != -1)
                    sb.append(cbuf, 0, read);
            }
			pub_COLUMN_NAME_OSM_ID_XML = sb.toString();
            in2 = new ByteArrayInputStream(sb.toString().getBytes());

            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = builder.parse(in2);
			if (doc != null) {
				NodeList nl = doc.getElementsByTagName("result");
				if (nl.getLength() > 0) {
					Node node = nl.item(0);
					NamedNodeMap attributes = node.getAttributes();
					osm_id = attributes.getNamedItem("osm_id").getNodeValue();
				}
				nl = doc.getElementsByTagName("road");
				if (nl.getLength() > 0) {
					Node node = nl.item(0);
					osm_road = node.getTextContent();
				}
			}
			pub_COLUMN_NAME_OSM_ID = osm_id;
			pub_COLUMN_NAME_OSM_ROAD = osm_road;
			insertIntoTable();
			
			//System.out.println(osm_id + " - " + osm_road);

			if (last_osm_id.equalsIgnoreCase(osm_id)) {
				Log.d("GPS", "osm_id didn't change...");
				return (new String[] {"",""});
			}
			last_osm_id = osm_id;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
	        try {
	            in.close();
	            in2.close();
	            reader.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }

			return (new String[] {osm_id,osm_road});
	}
			
		public final String[] getOSMSpeed(String osm_id) {

			String name = "";
			String maxspeed = "-";
			String highway = "";
			
			InputStream in = null;
			InputStream in2 = null;
			InputStreamReader reader = null;
			try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpGet httpPost = new HttpGet(
					"http://www.openstreetmap.org/api/0.6/way/" + osm_id
//					"http://www.openstreetmap.org/api/0.6/way/23200739"
					);

			HttpResponse response = httpClient.execute(httpPost, localContext);
			in = response.getEntity().getContent();

			reader = new InputStreamReader(in);
            StringBuffer sb = new StringBuffer();
            {
                int read;
                char[] cbuf = new char[1024];
                while ((read = reader.read(cbuf)) != -1)
                    sb.append(cbuf, 0, read);
            }
			pub_COLUMN_NAME_OSM_TAG_XML = sb.toString();
            in2 = new ByteArrayInputStream(sb.toString().getBytes());

			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(in2);
			if (doc != null) {
				NodeList nl = doc.getElementsByTagName("tag");
				for (int i = 0; i < nl.getLength(); i++) {
					Node node = nl.item(i);
					NamedNodeMap attributes = node.getAttributes();

					if (attributes.getNamedItem("k").getNodeValue()
							.equalsIgnoreCase("name")) {
						name = attributes.getNamedItem("v").getNodeValue();
					}

					if (attributes.getNamedItem("k").getNodeValue()
							.equalsIgnoreCase("maxspeed")) {
						maxspeed = attributes.getNamedItem("v").getNodeValue();
					}
					
					if (attributes.getNamedItem("k").getNodeValue()
							.equalsIgnoreCase("highway")) {
						highway = attributes.getNamedItem("v").getNodeValue();
					}
				}
			}
			
			if (maxspeed != pub_COLUMN_NAME_OSM_TAG_MAXSPEED) {
				pub_COLUMN_NAME_OSM_TAG_MAXSPEED = maxspeed;
				async_change_speed_color();
			}

			
			pub_COLUMN_NAME_OSM_TAG_HIGHWAY = highway;
			pub_COLUMN_NAME_OSM_TAG_NAME = name;
			insertIntoTable();
			
			//System.out.println("maxspeed = " + maxspeed);
			//System.out.println("highway = " + highway);
			//System.out.println("name = " + name);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
	        try {
	            in.close();
	            in2.close();
	            reader.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }

		return (new String[] {maxspeed,highway,name});
	}

	
	
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		try {

		String lat = String.valueOf(location.getLatitude());
		pub_COLUMN_NAME_GPS_LAT = lat;
		String lng = String.valueOf(location.getLongitude());
		pub_COLUMN_NAME_GPS_LON = lng;
		String gpsspeed = String.valueOf(location.getSpeed());
		if (!pub_COLUMN_NAME_GPS_SPEED.equals(""+(Float.parseFloat(gpsspeed) * 3.6 ))){
			pub_COLUMN_NAME_GPS_SPEED = ""+(Float.parseFloat(gpsspeed) * 3.6 );
			async_change_speed_color();
		}
		String accuracy = String.valueOf(location.getAccuracy());
		pub_COLUMN_NAME_GPS_ACCURACY = accuracy;
		insertIntoTable();
		
		Log.d("GPS", "location changed" 
				+ " - lat=" + lat
				+ " - lng=" + lng
				+ " - gpsspeed=" + (Float.parseFloat(gpsspeed) * 3.6 )
				+ " - accuracy=" + accuracy
				);
		latViwe.setText(lat);
		lonViwe.setText(lng);
		gpsspeedViwe.setText("" + Math.round(Float.parseFloat(gpsspeed) * 3.6 ));
		accuracyViwe.setText(accuracy);
		
		//async_change_speed_color();
		
		GetOSMIDTask task = new GetOSMIDTask();
		task.execute(new String[] { "http://nominatim.openstreetmap.org/reverse?lat=" + lat + "&lon=" + lng });//43.4618&lon=80.5311" });
		//task.execute(new String[] { "http://nominatim.openstreetmap.org/reverse?lat=43.4618&lon=80.5311" });
		//readWebpage(textView);


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		Log.d("GPS", "status changed to " + provider + " [" + status + "]");
	}

	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				gps_update_interval, 1, this);
		Log.d("###", "onResume");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("###", "onDestroy");
	    finish();
//		System.runFinalizersOnExit(true);
//	    System.exit(0);
	}

	@Override
	protected void onPause() {
		Log.d("###", "onPause");
		this.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		locationManager.removeUpdates(this);
		super.onPause();
	}
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

}